package com.songlanyun.modules.opus.entity;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.annotation.*;

import java.io.IOException;
import java.io.Serializable;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.type.TypeReference;
import com.songlanyun.common.drive.RootEntity;
import com.songlanyun.common.enums.CommentConstant;
import com.songlanyun.common.enums.GoodsConstant;
import com.songlanyun.common.enums.OpusConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.RedisKeys;
import com.songlanyun.common.utils.RedisUtils;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import com.songlanyun.modules.comment.entity.UserComment;
import com.songlanyun.modules.comment.service.UserCommentService;
import com.songlanyun.modules.like.entity.LikeRecord;
import com.songlanyun.modules.like.service.LikeRecordService;
import com.songlanyun.modules.opus.service.OpusGoodsService;
import com.songlanyun.modules.opus.service.OpusService;
import com.songlanyun.modules.opus.service.OpusThemeService;
import com.songlanyun.modules.opus.service.OpusThemeSystemService;
import com.songlanyun.modules.rabbitmq.util.SpringContextUtil;
import jodd.util.StringUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;

/**
 * 作品表
 *
 * @author lubo
 * @email sunlightcs@gmail.com
 * @date 2021-01-13 16:35:02
 */
@Data
@TableName("yxt_opus")
public class Opus extends RootEntity<Long, Opus> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     *
     */
    @TableId
    private Long id;
    /**
     * 作品标题
     */
    private String title;
    /**
     * 作品封面
     */
    private String cover;
    /**
     * 发布会员id（平台发布这里是0 ）
     */
    private Long publisherId;
    /**
     * 头像
     */
    @TableField(exist = false)
    private String headPhoto;
    /**
     * 用户昵称
     */
    @TableField(exist = false)
    private String nickname;
    /**
     * 用户手机号
     */
    @TableField(exist = false)
    private String mobile;
    /**
     * 作品类型（0图文，1视频）
     */
    private OpusConstant.OpusType opusType;
    /**
     * 0官方，1会员
     */
    private OpusConstant.PublisherType publisherType;
    /**
     * 审核说明
     */
    private String auditRemark;
    /**
     * 作品审核状态（0待审核，1通过审核，2审核不通过）
     */
    private OpusConstant.VerifyStatus opusStatus;
    /**
     * 管理员开通置顶
     */
    private Boolean openStick;
    /**
     * 审核时间
     */
    private Date auditTime;
    /**
     * 创建时间（发布时间）
     */
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    /**
     * 修改时间
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    /**
     * 作品内容
     */
    private String content;
    /**
     * 当是图文作品时，记录多张图片，最多10张，以数组形式记录
     */
    private String images;

    /**
     * 视频地址
     */
    private String mediaAddress;
    /**
     * 文件大小
     */
    private Long mediaSize;
    /**
     * 播放时长（单位秒）
     */
    private Integer duration;
    /**
     * 浏览人数
     */
    private Integer browseNum;

    public void addBrowseNum(Integer num) {
        this.browseNum = this.browseNum + num;
        loadOpusService().updateById(this);
    }

    /**
     * 点赞人数
     */
    private Integer likeNum;

    /**
     * 增加点赞数量
     *
     * @param num
     */
    public void addLikeNum(Integer num) {
        this.likeNum = this.likeNum + num;
        loadOpusService().updateById(this);
    }

    /**
     * 减少点赞数量
     *
     * @param num
     */
    public void subLikeNum(Integer num) {
        if (this.likeNum > num) {
            this.likeNum = this.likeNum - num;
        } else {
            this.likeNum = 0;
        }
        loadOpusService().updateById(this);

    }

    /**
     * 分享人数
     */
    private Integer shareNum;

    public void addShareNum(Integer num) {
        this.shareNum = this.shareNum + num;
        loadOpusService().updateById(this);
    }

    /**
     * 评论人数
     */
    private Integer commentNum;

    public void addCommentNum(Integer num) {
        this.commentNum = this.commentNum + num;
        loadOpusService().updateById(this);
    }

    /**
     * 浏览总数
     */
    private Integer browseSum;

    public void addBrowseSum(Integer num) {
        this.browseSum = this.browseSum + num;
        loadOpusService().updateById(this);
    }

    /**
     * 评论总数
     */
    private Integer commentSum;

    public void addCommentSum(Integer num) {
        this.commentSum = this.commentSum + num;
        loadOpusService().updateById(this);
    }

    /**
     * 分享总数
     */
    private Integer shareSum;

    public void addShareSum(Integer num) {
        this.shareSum = this.shareSum + num;
        loadOpusService().updateById(this);
    }

    public OpusService loadOpusService() {
        return (OpusService) SpringContextUtil.getBean("opusService");
    }


    /**
     * 所有话题（字符串逗号拼接）
     */
    @TableField(exist = false)
    private String opusThemeList;

    public void loadOpusThemeList() {
        OpusThemeSystemService service = (OpusThemeSystemService) SpringContextUtil.getBean("opusThemeSystemService");
        List<String> list = service.listByOpusId(this.getId());
        this.opusThemeList =StringUtil.join(list, ",");
    }

    /**
     * 所有商品
     */
    @TableField(exist = false)
    private List<OpusGoods> opusGoodsList;

    public void loadOpusGoodsList() {
        OpusGoodsService service = (OpusGoodsService) SpringContextUtil.getBean("opusGoodsService");
        this.opusGoodsList = service.listByOpusId(this.getId());
    }

    /**
     * 所有评论
     */
    @TableField(exist = false)
    private List<UserComment> userCommentList;

    public void loadUserCommentList() {
        UserCommentService service = (UserCommentService) SpringContextUtil.getBean("userCommentService");
        this.userCommentList = service.listByOpusId(this.getId(), CommentConstant.CommentModelType.OPUS);
    }

    /**
     * 是否关注
     */
    @TableField(exist = false)
    private Boolean isConcern;

    /**
     * 是否点赞
     */
    @TableField(exist = false)
    private Boolean isLike;

    /**
     * 是否是自己发布的
     */
    @TableField(exist = false)
    public Boolean isMe;

    public void loadIsMe(Long userId) {
        this.isMe = publisherId.equals(userId);
    }

    public void loadIsLike(Long userId) {
        LikeRecordService service = (LikeRecordService) SpringContextUtil.getBean("likeRecordService");
        //先查redis，再查数据库
        RedisUtils redisUtils = (RedisUtils) SpringContextUtil.getBean("redisUtils");

        BoundHashOperations<String, String, Object> data = redisUtils.boundHashOps(RedisKeys.BbsKey.LIKE_OPUS_KEY.getKey());
        HashMap<String, Object> userMap = (HashMap<String, Object>) data.get(getId() + "");
        String userIdStr = String.valueOf(userId);
        //查询redis是否点赞
        if (userMap != null) {
            if (userMap.containsKey(userIdStr)) {
                this.isLike = true;
            } else {
                this.isLike = service.isLike(userId, OpusConstant.ModelType.OPUS, getId());
            }
            //统计redis中所有点赞数
            int redisLikeNum = userMap.keySet().size();
            this.likeNum += redisLikeNum;
        } else {
            //查询数据库是否点赞
            this.isLike = service.isLike(userId, OpusConstant.ModelType.OPUS, getId());
        }
    }


    @Override
    public Long getIdentity() {
        return getId();
    }
}
